package com.yitong.equipment.network

import com.yitong.equipment.App
import com.yitong.equipment.ext.getBaseHost
import com.yitong.equipment.network.interceptor.CacheInterceptor
import com.yitong.equipment.network.interceptor.AppHeadInterceptor
import com.yitong.equipment.network.logging.LogInterceptor
import okhttp3.Cache
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import java.io.File
import java.util.concurrent.TimeUnit

class RetrofitManager private constructor(url: String) {
    private val mApiService: APIService

    init {
        initOkHttpClient()
        val retrofit = Retrofit.Builder()
                       .baseUrl(url)
                       .addConverterFactory(GsonConverterFactory.create())
                       .addCallAdapterFactory(RxJava2CallAdapterFactory.create()).client(mOkHttpClient)
                       .build()
        mApiService = retrofit.create(APIService::class.java)
    }

    companion object {
        const val TIMEOUT = 15
        @Volatile
        private var mOkHttpClient: OkHttpClient? = null
        var managers: MutableMap<String, RetrofitManager> = HashMap()
        private var release_url = getBaseHost()
        const val test_url = ""

        private fun getInstance(url: String): RetrofitManager {
            var instance = managers[url]
            if (instance == null) {
                instance = RetrofitManager(url)
                managers[url] = instance
            }
            return instance
        }

        val instance: RetrofitManager
            get() = getInstance(release_url)

        @JvmStatic
        val apiService: APIService
            get() = instance.mApiService

        fun getAPIService(url: String): APIService {
            return getInstance(url).mApiService
        }
    }


    private fun initOkHttpClient() {
        if (mOkHttpClient == null) {
            synchronized(RetrofitManager::class.java) {
                if (mOkHttpClient == null) { // 指定缓存路径,缓存大小100Mb
                    mOkHttpClient = OkHttpClient.Builder()
                        .cache(Cache(File(App.instance.cacheDir, "yt_cache"), 10 * 1024 * 1024))
                        //添加公共heads 注意要设置在日志拦截器之前，不然Log中会不显示head信息
                        .addInterceptor(AppHeadInterceptor())
                        ////添加缓存拦截器 可传入缓存天数，不传默认7天
                        .addInterceptor(CacheInterceptor(3))
                        // 日志拦截器
                        .addInterceptor(LogInterceptor())
                        //错误重连 超时时间 连接、读、写
                        .retryOnConnectionFailure(false)
                        .connectTimeout(TIMEOUT.toLong(), TimeUnit.SECONDS)
                        .readTimeout(TIMEOUT.toLong(), TimeUnit.SECONDS)
                        .writeTimeout(TIMEOUT.toLong(), TimeUnit.SECONDS).build()
                }
            }
        }
    }
}